﻿/*******************************************************************************
 * Creator:admin 2022-05-07 19:30:26
 * Description: YoursLC有源低代码
*********************************************************************************/

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Think9.Controllers.Basic;
using Think9.Models;
using Think9.Services.Base;
using Think9.Services.Basic;
using Think9.Services.CodeBuild;
using Think9.Services.Flow;
using Think9.Services.Table;

namespace Think9.Controllers.CodeBuild
{
    public class Data02Controller : BaseController
    {
        private Data02Service Data02Service = new Data02Service();
        private ComService ComService = new ComService();

        private readonly string _maintbid = "tb_Data02";//主表编码
        private readonly string _flowid = "bi_Data02";//流程编码 bi_基础信息 fw_一般录入表
        private readonly string _tbname = "Data02行政区划";//录入表名称

        private readonly string split = BaseUtil.ComSplit;//字符分割 用于多选项的分割等
        private string str;

        #region list列表
        public override ActionResult Index(int? id)
        {
            string err = CheckCom.CheckedBeforeBegin(_flowid);//检查数据库是否建表等
            if (string.IsNullOrEmpty(err))
            {
                object param = BasicHelp.GetParamObject(CurrentUser);//系统参数可作为数据规范的条件参数
                ViewBag.SelectList = Data02Service.GetSelectList("list", param);//为查询条件(下拉选择)准备动态数据
                ViewBag.SearchMode = BasicHelp.GetSearchMode(_flowid);//查看编辑模式-录入表管理/权限设置可设置

                base.Index(id);
                return View();
            }
            else
            {
                return Json(err);
            }
        }

        /// <summary>
        /// 操作前判断及数据处理，列表页面点击新增数据按钮触发
        /// </summary>
        /// <param name="type">类型add</param>
        /// <param name="listid">自增长id</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult BeforeAdd(string type, string listid)
        {
            string err = "";
            int _listid = 0;//自动编号及子表数据初始化等情况需插入一条空数据并返回自增长id
            try
            {
                //使用通用函数得到步骤第一步，基本信息录入表返回空
                CurrentPrcsEntity mPrcs = FlowCom.GetFistFlowStept(_flowid);
                err = mPrcs == null ? "" : mPrcs.ERR;

                if (string.IsNullOrEmpty(err))
                {
                    //使用通用函数添加前检测，如权限校验、录入表是否被禁用等
                    err = CheckCom.CheckedBeforeAdd(_flowid, mPrcs, CurrentUser);
                    if (string.IsNullOrEmpty(err))
                    {
                        //添加前处理，如自动编号及子表数据初始化等
                        _listid = Data02Service.BeforeAdd(ref err, _flowid, _maintbid, _tbname, mPrcs, CurrentUser);

                    }
                }

                if (string.IsNullOrEmpty(err))
                {
                    string pid = mPrcs == null ? "-1" : mPrcs.PrcsId;//当前流程步骤id
                    return Json(SuccessTip("", _listid.ToString(), pid));
                }
                else
                {
                    return Json(ErrorTip(err));
                }
            }
            catch (Exception ex)
            {
                return Json(ErrorTip(ex.Message));
            }
        }

        /// <summary>
        /// 操作前判断及数据处理，列表页面点击编辑按钮触发
        /// </summary>
        /// <param name="type">类型edit</param>
        /// <param name="listid">自增长id：基础信息表对应本表字段listid，一般录入表对应表flowrunlist中的listid</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult BeforeEdit(string type, string listid)
        {
            string err = "";
            //使用通用函数得到当前流程步骤，基本信息录入表返回空
            CurrentPrcsEntity mPrcs = FlowCom.GetCurrentFlowStept(_flowid, listid);
            err = mPrcs == null ? "" : mPrcs.ERR;

            if (string.IsNullOrEmpty(err))
            {
                //使用通用函数编辑前检测-如权限校验、录入表是否被禁用、是否锁定等
                err = CheckCom.CheckedBeforeEdit(_flowid, listid, mPrcs, CurrentUser);
                if (string.IsNullOrEmpty(err))
                {
                    //编辑前数据处理，可手动精简
                    err = Data02Service.BeforeEdit(_flowid, listid, mPrcs, CurrentUser);
                }
            }

            if (string.IsNullOrEmpty(err))
            {
                string pid = mPrcs == null ? "-1" : mPrcs.PrcsId;//当前流程步骤id
                return Json(SuccessTip("", listid, pid));
            }
            else
            {
                return Json(ErrorTip(err));
            }
        }

        /// <summary>
        /// 数据查看-列表页面点击查看按钮触发
        /// </summary>
        /// <param name="listid">基础信息表对应本表字段listid，一般录入表对应表flowrunlist中的listid</param>
        /// <returns></returns>
        [HttpGet]
        public  ActionResult Detail(string listid)
        {
            TbBasicEntity model = PageCom.GetAttBut(listid, _flowid);//得到附件按钮设置，可在录入表管理/页面按钮中设置

            ViewBag.ListId = listid;
            ViewBag.ButAtt = model.ButAtt;//附件按钮是否显示 1显示
            ViewBag.ButAttTxt = model.ButAttTxt;//附件按钮标题
            ViewBag.UserId = CurrentUser == null ? "un_defined" : CurrentUser.Account;

            return View();
        }

        /// <summary>
        /// 数据删除 列表页面点击删除按钮触发
        /// </summary>
        /// <param name="listid">基础信息表对应本表字段listid，一般录入表对应表flowrunlist中的listid</param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult Delete(string listid)
        {
            string err = "";

            //使用通用函数得到当前流程步骤 基本信息录入表返回空
            CurrentPrcsEntity mPrcs = FlowCom.GetCurrentFlowStept(_flowid, listid);
            err = mPrcs == null ? "" : mPrcs.ERR;

            if (string.IsNullOrEmpty(err))
            {
                //删除前检测 包括权限校验、录入表是否被禁用、数据是否锁定等
                err = CheckCom.CheckedBeforeDel(_flowid, listid, mPrcs, CurrentUser);
            }

            try
            {
                if (string.IsNullOrEmpty(err))
                {
                    err = Data02Service.DeleteByID(listid, _flowid) ? "" : "操作失败";
                    //删除后数据处理,默认什么也不做，可手动删除
                    if (string.IsNullOrEmpty(err))
                    {
                        err = Data02Service.AfterDelete(_flowid, listid, mPrcs, CurrentUser);
                    }
                }

                if (string.IsNullOrEmpty(err))
                {
                    Record.AddRecord(listid, _flowid, "数据删除", CurrentUser);
                    return Json(SuccessTip("删除成功"));
                }
                else
                {
                    return Json(ErrorTip(err));
                }
            }
            catch (Exception ex)
            {
                return Json(ErrorTip(ex.Message));
            }
        }

        /// <summary>
        /// 数据查询，列表页面点击查询按钮触发
        /// </summary>
        /// <param name="model">主表数据model</param>
        /// <param name="pageInfo">页面信息，包括行数、排序等</param>
        /// <param name="isAll">为all则显示所有</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult GetPageListBySearch(Data02Model model, PageInfoEntity pageInfo, string isAll)
        {
            object param = BasicHelp.GetParamObject(CurrentUser);

            pageInfo.field = "listid";//排序field
            pageInfo.order = "desc";

            Data02Model entity = new Data02Model();
            if (string.IsNullOrEmpty(isAll))
            {
                entity = model;
            }

            long total = 0;
            //主表查询返回数据列表，备注：查询条件可在录入表指标属性中设置
            IEnumerable<dynamic> list = Data02Service.GetPageListBySearch(ref total, entity, pageInfo, CurrentUser, _flowid, _maintbid);
            //下拉选择、多选、单选准备动态数据源
            IEnumerable<valueTextEntity> SelectList = Data02Service.GetSelectList("list", param);

            //处理列表数据select、checkbox、radio等Value与Text转化
            foreach (Data02Model obj in list)
            {

            }

            if (list == null)
            {
                return Json(ErrorTip("参数错误"));
            }
            else
            {
                var result = new { code = 0, msg = "", count = total, data = list };
                return Json(result);
            }
        }
        #endregion list列表

        #region Form编辑
        /// <summary>
        /// 录入页面显示
        /// </summary>
        /// <param name="type">add或edit</param>
        /// <param name="listid">基础信息表对应本表字段listid，一般录入表对应表flowrunlist中的listid</param>
        /// <param name="pid">当前流程步骤id</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Form(string type, string listid, string pid)
        {
            int _listid = listid == null ? 0 : int.Parse(listid);
            object param = BasicHelp.GetParamObject(CurrentUser);//数据规范中的筛选条件可使用系统参数
            ViewBag.UserId = CurrentUser == null ? "un_defined" : CurrentUser.Account;//用户id
            ViewBag.Type = type;//add或edit
            ViewBag.ListId = _listid;//基础信息表listid自增长，一般录入表listid来源于flowrunlist
            ViewBag.Split = split;//字符分割 checkbox多选时使用
            ViewBag.FId = _flowid;//流程编码
            ViewBag.PrcId = pid;//流程步骤id
            ViewBag.PrcNo = FlowCom.GetFlowNoByID(_flowid, pid);//流程步骤编码
            ViewBag.SelectList = Data02Service.GetSelectList(type, param);//为下拉选择、多选、单选动态数据源赋值

            Data02Model model = new Data02Model();
            if (type == "add")
            {
                model.ListId = _listid;
                if (_listid != 0)
                {
                    model = Data02Service.GetByWhereFirst("where listid=" + _listid + "");
                }
                //赋初始值--系统指标或默认值

            }
            else
            {
                model = Data02Service.GetByWhereFirst("where listid=" + _listid + "");
            }

            if (model != null)
            {
                return View(model);
            }
            else
            {
                return Json("数据不存在");
            }
        }

        /// <summary>
        /// 下拉选择或者弹出选择后调用，完成数据读取功能--可在录入表管理/数据读取中自定义
        /// </summary>
        /// <param name="controlslist">页面控件id与text</param>
        /// <param name="gridlist">子表数据列表 无子表时为空</param>
        /// <param name="id"></param>
        /// <param name="tbid">主表id</param>
        /// <param name="indexid">下拉或者弹出选择(触发控件)对应指标编码</param>
        /// <param name="value">下拉或者弹出选择(触发控件)对应控件Value</param>
        /// <returns>返回list交由前台解析</returns>
        [HttpPost]
        public ActionResult AfterControlSelect(IEnumerable<ControlEntity> controlslist, IEnumerable<GridListEntity> gridlist, string id, string tbid, string indexid, string value)
        {
            try
            {
                //未设置数据读取则什么也不做
                List<ControlEntity> list = new List<ControlEntity>();

                return Json(SuccessTip("", list, ""));
            }
            catch (Exception ex)
            {
                return Json(ErrorTip(ex.Message));
            }
        }

        /// <summary>
        /// 数据保存 ，Form页面点击保存按钮触发
        /// </summary>
        /// <param name="model">主表数据model</param>
        /// <param name="gridlist">子表数据 无子表时为空</param>
        /// <param name="listid">listid=0表示增加</param>
        /// <param name="prcno">流程步骤编码</param>
        /// <param name="type">add或edit</param>
        /// <param name="att">附件id</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveData(Data02Model model, IEnumerable<GridListEntity> gridlist, int listid, string prcno, string type, string att)
        {
            string err = "";

            try
            {
                //编辑
                if (listid != 0)
                {
                    err = this.Edit(model, gridlist, listid, prcno);
                }
                else
                {
                    listid = this.Add(ref err, prcno, model);

                }

                if (string.IsNullOrEmpty(err))
                {
                    err = Data02Service.AfterEdit(listid.ToString(), _flowid, FlowCom.GetFlowIDByNo(_flowid, prcno), CurrentUser);//编辑后数据处理，可手动删除

                    if (string.IsNullOrEmpty(err))
                    {
                        return Json(SuccessTip("操作成功"));
                    }
                    else
                    {
                        return Json(ErrorTip("AfterEdit函数出现错误：" + err));
                    }
                }
                else
                {
                    return Json(ErrorTip("操作失败！" + err));
                }
            }
            catch (Exception ex)
            {
                return Json(ErrorTip(ex.Message));
            }
        }

        /// <summary>
        /// 转交下一步，Form页面点击转交按钮触发，可手动删除
        /// </summary>
        /// <param name="model">主表数据model</param>
        /// <param name="gridlist">子表数据列表 无子表时为空</param>
        /// <param name="listid">listid=0表示增加</param>
        /// <param name="prcno">流程步骤编码</param>
        /// <param name="type">add或edit</param>
        /// <param name="att">附件id</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult NextStep(Data02Model model, IEnumerable<GridListEntity> gridlist, int listid, string prcno, string type, string att)
        {
            string err = "";

            try
            {
                //编辑
                if (listid != 0)
                {
                    err = this.Edit(model, gridlist, listid, prcno);
                }
                else
                {
                    listid = this.Add(ref err, prcno, model);

                }

                if (string.IsNullOrEmpty(err))
                {
                    err = Data02Service.AfterEdit(listid.ToString(), _flowid, FlowCom.GetFlowIDByNo(_flowid, prcno), CurrentUser);//编辑后数据处理，可手动删除

                    if (string.IsNullOrEmpty(err))
                    {
                        if (_flowid.StartsWith("bi_"))
                        {
                          return Json(ErrorTip("数据保存成功，基本信息表不能被转交"));
                        }
                        else
                        {
                          return Json(SuccessTip("", listid.ToString()));
                        }
                    }
                    else
                    {
                        return Json(ErrorTip("AfterEdit函数出现错误：" + err));
                    }
                }
                else
                {
                    return Json(ErrorTip(err));
                }
            }
            catch (Exception ex)
            {
                return Json(ErrorTip(ex.Message));
            }
        }

        /// <summary>
        /// 结束 ，Form页面点击结束按钮触发，可手动删除
        /// </summary>
        /// <param name="model">主表数据model</param>
        /// <param name="gridlist">子表数据 无子表时为空</param>
        /// <param name="listid">listid=0表示增加</param>
        /// <param name="prcno">流程步骤编码</param>
        /// <param name="type">add或edit</param>
        /// <param name="att">附件id</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Finish(Data02Model model, IEnumerable<GridListEntity> gridlist, int listid, string prcno, string type, string att)
        {
            string err = "";

            try
            {
                //编辑
                if (listid != 0)
                {
                    err = this.Edit(model, gridlist, listid, prcno);
                }
                else
                {
                    listid = this.Add(ref err, prcno, model);

                }

                if (string.IsNullOrEmpty(err))
                {
                    err = Data02Service.AfterFinish(listid.ToString(), _flowid, FlowCom.GetFlowIDByNo(_flowid, prcno), CurrentUser);//完成后数据处理，可手动删除

                    if (string.IsNullOrEmpty(err))
                    {
                        if (_flowid.StartsWith("bi_"))
                        {
                            return Json(ErrorTip("操作成功，数据已被锁定"));
                        }
                        else
                        {
                            return Json(SuccessTip("操作成功"));
                        }
                    }
                    else
                    {
                        return Json(ErrorTip("AfterFinish函数出现错误：" + err));
                    }
                }
                else
                {
                    return Json(ErrorTip("操作失败！" + err));
                }
            }
            catch (Exception ex)
            {
                return Json(ErrorTip(ex.Message));
            }
        }

        //添加主表数据
        private int Add(ref string err, string prcno, Data02Model model)
        {
            int listid = 0;

            DataTable dtMain = DataTableHelp.ModelToDataTable<Data02Model>(model);//model转换DataTable
            //通用函数进行主键和唯一键检测，主键和唯一键可在录入表指标属性中设置
            err = CheckCom.CheckMainTbValueBKAndUnique(listid, _maintbid, model, dtMain);
            if (string.IsNullOrEmpty(err))
            {
                //通用函数进行主表自定义校验，自定义校验可在录入表管理/录入校验中设置
                err = CheckCom.CheckMainTbValidate(dtMain, _flowid, prcno);
                if (string.IsNullOrEmpty(err))
                {
                    if (CurrentUser != null)
                    {
						model.BeginTime = DateTime.Now.ToString();
						model.isLock = "0";
						model.BeginUser = CurrentUser.Account;
						model.BeginDept = CurrentUser.DeptNo;
						model.BeginDeptStr = CurrentUser.DeptNoStr;
						model.RunName = BaseUtil.GetRunName(CurrentUser.Account, _flowid, _tbname, dtMain);
						
						listid = Data02Service.InsertReturnID(model);
						
						err = listid > 0 ? "" : "添加失败";
						if (string.IsNullOrEmpty(err))
						{
							Record.AddRecord(listid.ToString(), _flowid, "数据添加", CurrentUser);
						}
                    }
                    else
                    {
                        err = "当前用户对象为空";
                    }
                }
            }

            return listid;
        }

        //编辑主表数据
        private string Edit(Data02Model model, IEnumerable<GridListEntity> gridlist, int listid, string prcno)
        {
            string err = "";

            //有子表时会遍历数据并判断取数


            if (string.IsNullOrEmpty(err))
            {
                model.ListId = listid;

                DataTable dtMain = DataTableHelp.ModelToDataTable<Data02Model>(model);
                //主键和唯一检测，主键和唯一可在录入表指标属性中设置
                err = CheckCom.CheckMainTbValueBKAndUnique(listid, _maintbid, model, dtMain);
                if (string.IsNullOrEmpty(err))
                {
                    //自定义校验，自定义校验可在录入表管理录入校验中设置
                    err = CheckCom.CheckTbValidate(dtMain, gridlist, _flowid, prcno);
                    if (string.IsNullOrEmpty(err))
                    {
                        //子表数据编辑
		

                        string updateFields = Data02Service.GetUpdateFields(prcno);//可编辑列
                        if(!string.IsNullOrEmpty(updateFields))
                        {

                            //编辑主表
                            err = Data02Service.UpdateByWhere("where listid=" + listid + "", updateFields, model) > 0 ? "" : "编辑失败";
                        }

                        Record.AddRecord(listid.ToString(), _flowid, "数据编辑", CurrentUser);
                    }
                }
            }

            return err;
        }


        #endregion Form编辑




    }
}